package org.jeecg.modules.mes.chiefdata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.NumberUtils;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataBomitem;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataMateriel;
import org.jeecg.modules.mes.chiefdata.mapper.MesChiefdataBomitemMapper;
import org.jeecg.modules.mes.chiefdata.service.IMesChiefdataBomitemService;
import org.jeecg.modules.mes.chiefdata.service.IMesChiefdataMaterielService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Description: BOM—数据项
 * @Author: jeecg-boot
 * @Date: 2020-10-20
 * @Version: V1.0
 */
@Service
@Log4j2
public class MesChiefdataBomitemServiceImpl extends ServiceImpl<MesChiefdataBomitemMapper, MesChiefdataBomitem> implements IMesChiefdataBomitemService {

    @Autowired
    private MesChiefdataBomitemMapper mesChiefdataBomitemMapper;
    @Autowired
    private IMesChiefdataMaterielService mesChiefdataMaterielService;
    @Autowired
    private ISysDictService sysDictService;

    @Override
    public List<MesChiefdataBomitem> selectByMainId(String mainId) {
        return mesChiefdataBomitemMapper.selectByMainId(mainId);
    }

    /**
     * 根据成品物料id查询bomid，再查询出bomitem数据
     *
     * @param materialId
     * @return
     */
    public List<MesChiefdataBomitem> selectByMaterialId(String materialId) {
        return mesChiefdataBomitemMapper.selectByMaterialId(materialId);
    }

    @Transactional
    public Result<?> importMesChiefdataBomitem(Map<String, MultipartFile> fileMap, String mainId) {
    	StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		int successNum = 0;
		int failureNum = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                int i = 0;
                List<MesChiefdataBomitem> list = ExcelImportUtil.importExcel(file.getInputStream(), MesChiefdataBomitem.class, params);
                for (MesChiefdataBomitem temp : list) {
                    i++;
                    long start = System.currentTimeMillis();
                    log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
					if(StringUtils.isBlank(temp.getMaterielName())){
						throw new RuntimeException("第"+i+"行，料件名称不能为空！");
					}
					if(StringUtils.isBlank(temp.getUnit())){
						throw new RuntimeException("第"+i+"行，单位 不能为空！");
					}
					if(StringUtils.isBlank(temp.getMaterielType())){
						throw new RuntimeException("第"+i+"行，料件类型 不能为空！");
					}
					if(StringUtils.isBlank(temp.getMaterielGauge())){
						throw new RuntimeException("第"+i+"行，料件规格 不能为空！");
					}
					if(StringUtils.isBlank(temp.getMaterielGrade())){
						throw new RuntimeException("第"+i+"行，物料阶别 不能为空！");
					}
					if (this.checkProduceGrade(temp.getMaterielGrade())) {
						throw new RuntimeException("第" + i + "行，生产阶别错误！请检查！");
					}
					if(StringUtils.isBlank(temp.getIntangibleRate())){
						throw new RuntimeException("第"+i+"行，损耗率 不能为空！");
					}
					if(StringUtils.isBlank(temp.getQuantity())){
						throw new RuntimeException("第"+i+"行，正面用量 不能为空！");
					}
					if(StringUtils.isBlank(temp.getClientCode())){
						throw new RuntimeException("第"+i+"行，客户料号 不能为空！");
					}
					if(!"PCB".equals(temp.getMaterielType())&&!"物料".equals(temp.getMaterielType())){
						throw new RuntimeException("料件类型必须为大写PCB或者物料");
					}
					if (StringUtils.isNotBlank(temp.getMaterielCode())) {
						QueryWrapper<MesChiefdataBomitem> queryWrapper = new QueryWrapper<>();
						queryWrapper.eq("materiel_code", temp.getMaterielCode()).eq("bom_id", mainId).eq("materiel_grade",temp.getMaterielGrade());
						List<MesChiefdataBomitem> mesChiefdataBomitemList = this.list(queryWrapper);
						if (mesChiefdataBomitemList.size() == 0) {
							temp.setBomId(mainId);
							temp.setQuantity(NumberUtils.getNumber_charAt(temp.getQuantity()));

							//查询是否有物料信息，没有的话新增物料信息
							QueryWrapper<MesChiefdataMateriel> queryWrapper1 = new QueryWrapper<>();
							queryWrapper1.eq("materiel_code",temp.getMaterielCode());
							List<MesChiefdataMateriel> list1 = mesChiefdataMaterielService.list(queryWrapper1);
							if(list1.size()==0){
								if (StringUtils.isNotBlank(temp.getClientCode())&&!"无".equals(temp.getClientCode().trim())) {
									QueryWrapper<MesChiefdataMateriel> queryWrapper2 = new QueryWrapper<>();
									queryWrapper2.eq("query2", temp.getClientCode());
									List<MesChiefdataMateriel> list2 = mesChiefdataMaterielService.list(queryWrapper2);
									if (list2.size() != 0 && !list2.get(0).getMaterielCode().equals(temp.getMaterielCode())) {
//										throw new RuntimeException("已存在客户料号为:"+temp.getClientCode()+"的内部料号为："+list2.get(0).getMaterielCode()+"与现有内部料号不相同！");
										failureNum++;
										failureMsg.append("\n 第"+i+"行物料料号 " + temp.getMaterielCode() + "已存在客户料号为:"+temp.getClientCode()+"的内部料号"+list2.get(0).getMaterielCode());
									}
								}
								MesChiefdataMateriel mesChiefdataMateriel = new MesChiefdataMateriel();
								mesChiefdataMateriel.setMaterielCode(temp.getMaterielCode());
								mesChiefdataMateriel.setProductCode(temp.getProductCode());
								mesChiefdataMateriel.setProductName(temp.getMaterielName());
								mesChiefdataMateriel.setUnit(temp.getUnit());
								mesChiefdataMateriel.setMaterielType(temp.getMaterielType());
								mesChiefdataMateriel.setGauge(temp.getMaterielGauge());
								mesChiefdataMateriel.setProduceGrade(temp.getMaterielGrade());
								mesChiefdataMateriel.setQuery2(temp.getClientCode());
								mesChiefdataMaterielService.save(mesChiefdataMateriel);
							}
							mesChiefdataBomitemMapper.insert(temp);
						}
						successNum++;
						successMsg.append("\n 第"+i+"行物料料号 " + temp.getMaterielCode() + " 导入成功");
					} else {
//						throw new RuntimeException("物料料号不能为空！");
						failureNum++;
						failureMsg.append("\n 第"+i+"行物料料号不能为空！");
					}
				}
				long start = System.currentTimeMillis();
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
		if (failureNum > 0)
		{
			failureMsg.insert(0, "警告！共 " + failureNum + " 条数据格式不正确，错误如下：");
			return Result.ok(failureMsg.toString());
		}
		else
		{
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
			return Result.OK(successMsg.toString());
		}
    }

    /**
     * 根据物料成品料号和详细物料料号，查询物料详细信息
     *
     * @param machinesortCode
     * @param materielCode
     * @return
     */
    public MesChiefdataBomitem getsfg(String machinesortCode, String materielCode) {

        return mesChiefdataBomitemMapper.getsfg(machinesortCode, materielCode);
    }

    private boolean checkProduceGrade(String produceGrade) {
        List<DictModel> dictModels = sysDictService.queryDictItemsByCode("produce_grade");
        for (DictModel dm : dictModels) {
            if (produceGrade.equals(dm.getValue())) {
                return false;
            }
        }
        return true;
    }
}
